import threading
import socket
import json
from channels.generic.websocket import WebsocketConsumer


class ConsumerUAV(WebsocketConsumer):
    def connect(self):
        # 接受 WebSocket 连接
        self.accept()
        # 启动 UDP 线程
        self.udp_thread = threading.Thread(target=self.start_udp_server)
        self.udp_thread.daemon = True  # 确保主线程结束时，UDP线程也结束
        self.udp_thread.start()

    def disconnect(self, close_code):
        # 处理 WebSocket 断开连接时的逻辑
        pass

    def start_udp_server(self):
        # 设置 UDP 套接字
        udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        udp_socket.bind(('150.158.186.245', 5001))  # 设置监听地址和端口

        while True:
            # 接收 UDP 数据
            data, addr = udp_socket.recvfrom(1024)  # 缓冲区大小为 1024 字节
            if data:
                # 处理接收到的数据
                self.handle_udp_data(data.decode())

    def handle_udp_data(self, data):
        try:
            # JSON 字符串，包含纬度和经度
            json_data = json.loads(data)
            latitude = json_data.get('经度')
            longitude = json_data.get('纬度')
            speed = json_data.get('空速')
            roll = json_data.get('roll')
            pitch = json_data.get('pitch')
            yaw = json_data.get('yaw')
            # 将经纬度信息发送到前端
            self.send(text_data=json.dumps({
                'message': '接收到的无人机飞行信息',
                'latitude': latitude,
                'longitude': longitude,
                'speed': speed,
                'roll': roll,
                'pitch': pitch,
                'yaw': yaw
            }))
        except json.JSONDecodeError:
            print("Received invalid JSON data:", data)
